from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime, timedelta

from ..core.database import get_db
from ..models.transaction import Transaction
from ..schemas.query import TransactionResponse
from ..schemas.query import FESRequest, FESResponse
from ..core.tcp_client import send_xml_request
from ..core.xml_builder import build_request_xml
import xml.etree.ElementTree as ET
import logging

router = APIRouter()

def parse_xml_response(response_xml: str) -> dict:
    """解析XML响应"""
    root = ET.fromstring(response_xml)
    
    # 构建响应数据
    response_data = {
        "trans_code": root.find("trans_code").text,
        "bank_date": root.find("bank_date").text,
        "resp_code": root.find("resp_code").text,
        "orderid": root.find("orderid").text,
        "org_orderid": root.find("org_orderid").text if root.find("org_orderid") is not None else None,
        "org_trans_sn": root.find("org_trans_sn").text if root.find("org_trans_sn") is not None else None,
        "org_resp_code": root.find("org_resp_code").text if root.find("org_resp_code") is not None else None,
        "org_rrn": root.find("org_rrn").text if root.find("org_rrn") is not None else None,
        "pan": root.find("pan").text if root.find("pan") is not None else None
    }
    
    return response_data

@router.get("/transactions", response_model=List[TransactionResponse])
async def get_transactions(
    db: Session = Depends(get_db),
    pan: Optional[str] = None,
    orderid: Optional[str] = None,
    trans_code: Optional[str] = None,
    start_date: Optional[str] = Query(None, description="开始日期（YYYYMMDD）"),
    end_date: Optional[str] = Query(None, description="结束日期（YYYYMMDD）"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页记录数")
):
    """获取交易记录
    
    Args:
        pan: 卡号，可选
        orderid: 订单号，可选
        trans_code: 交易类型，可选（CEP: 消费，CEF: 退货）
        start_date: 开始日期（YYYYMMDD），可选，默认为最近7天
        end_date: 结束日期（YYYYMMDD），可选，默认为当前日期
        page: 页码，默认为1
        page_size: 每页记录数，默认为20，最大100
    """
    query = db.query(Transaction)
    
    # 只查询成功的消费和退货交易
    query = query.filter(
        Transaction.resp_code.in_(['0', '0000']),  # 只查询成功的交易
        Transaction.trans_code.in_(['CEP', 'CEF'])  # 只查询消费和退货
    )
    
    # 如果没有指定日期范围，默认查询最近7天的记录
    if not start_date and not end_date:
        today = datetime.now()
        end_date = today.strftime("%Y%m%d")
        start_date = (today - timedelta(days=7)).strftime("%Y%m%d")
    
    if pan:
        query = query.filter(Transaction.pan == pan)
    if orderid:
        query = query.filter(Transaction.orderid == orderid)
    if trans_code:
        if trans_code in ['CEP', 'CEF']:  # 只允许查询消费和退货
            query = query.filter(Transaction.trans_code == trans_code)
    if start_date:
        query = query.filter(Transaction.trans_date >= start_date)
    if end_date:
        query = query.filter(Transaction.trans_date <= end_date)
        
    # 计算总记录数
    total_count = query.count()
    
    # 按创建时间倒序排序
    query = query.order_by(Transaction.created_at.desc())
    
    # 分页
    offset = (page - 1) * page_size
    query = query.offset(offset).limit(page_size)
        
    transactions = query.all()
    
    # 构建响应头部信息
    response_headers = {
        "X-Total-Count": str(total_count),
        "X-Page": str(page),
        "X-Page-Size": str(page_size),
        "X-Total-Pages": str((total_count + page_size - 1) // page_size)
    }
    
    return transactions

@router.get("/transactions/{orderid}", response_model=TransactionResponse)
async def get_transaction(orderid: str, db: Session = Depends(get_db)):
    """根据订单号获取交易记录"""
    transaction = db.query(Transaction).filter(Transaction.orderid == orderid).first()
    if not transaction:
        raise HTTPException(status_code=404, detail="Transaction not found")
    return transaction 

@router.post("/fes")
async def query_transaction_status(request: FESRequest, db: Session = Depends(get_db)):
    try:
        # 根据原交易的pay_order查询原交易记录
        original_transaction = db.query(Transaction).filter(
            Transaction.pay_order == request.org_pay_order,
            Transaction.trans_code.in_(["CEP", "CEF"])
        ).first()
        
        if not original_transaction:
            raise HTTPException(
                status_code=404,
                detail=f"Original transaction with pay_order {request.org_pay_order} not found"
            )

        # 使用原交易的orderid作为org_orderid
        request_dict = request.dict(exclude={'org_pay_order'})  # 排除org_pay_order字段
        request_dict['org_orderid'] = original_transaction.orderid  # 使用数据库中查询到的orderid
        
        # 构建XML请求
        logging.info(f"FES请求数据: {request_dict}")
        request_xml = build_request_xml(request_dict)
        logging.info(f"FES请求XML: {request_xml}")
        
        # 发送请求到卡系统
        response_xml = await send_xml_request(request_xml)
        logging.info(f"FES响应XML: {response_xml}")
        
        # 解析响应
        response_dict = parse_xml_response(response_xml)
        
        return response_dict
    except Exception as e:
        logging.error(f"[FES] {str(e)} | orderid={request.orderid} | org_pay_order={request.org_pay_order}")
        raise HTTPException(status_code=500, detail=str(e)) 